import 'dart:async';
import 'package:get/get.dart';

import 'state.dart';

class AudioLogic extends GetxController {
  final state = AudioState();
  Timer? timer;

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    timer?.cancel();
    super.onClose();
  }

  void startPlay(String msgId) {
    state.playMap[msgId] = true;
    update();
    startAnimation();
  }

  void stopPlay(String msgId) {
    state.playMap[msgId] = false;
    timer?.cancel();
    stopAnimation();
    update();
  }

  void startAnimation() {
    timer = Timer.periodic(Duration(milliseconds: 300), (timer) {
      if (state.imageIndex == 0) {
        state.playImage = 'voice_msg_playing_1.png';
      } else if (state.imageIndex == 1) {
        state.playImage = 'voice_msg_playing_2.png';
      } else {
        state.playImage = 'voice_msg_playing_3.png';
      }
      state.imageIndex++;
      if (state.imageIndex > 2) {
        state.imageIndex = 0;
      }
      update();
    });
  }

  ///当前语音是否正在播放
  bool isPlaying(String msgId) {
    return state.playMap[msgId] != null && (state.playMap[msgId] ?? false);
  }

  void stopAnimation() {
    state.imageIndex = 0;
    timer?.cancel();
  }
}
